<template>
  <div class="upload-file" :class="fileList.length > limit ? 'hide' : ''">
    <el-upload
      ref="uploadRef"
      slot="tip"
      :action="model ? baseurl + 'base/import?model=' + tablename : baseurl + tablename + '/import'"
      :file-list="fileList"
      :limit="limit"
      multiple
      list-type="text"
      name="excel"
      :on-preview="handleDownload"
      :on-remove="handleRemove"
      :on-success="OnSuccess"
    >
      <el-button type="primary">上传导入文件</el-button>
      <!-- <template #tip>
        <div class="el-upload__tip">请上传xls文件</div>
      </template> -->
    </el-upload>
  </div>
</template>
<script lang="ts" setup>
//组建说明：本组建用于上传图片使用。
//出现打包后无法上传图片情况时候

//第一步：node_modules\mockjs\dist\mock.js
//搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;
//第二步：\node_modules\mockjs\src\mock\xhr\xhr.js
//搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;

defineOptions({
  name: 'ImportData',
})

const props = defineProps({
  tablename: {
    //表名
    type: String,
    default: '',
  },
  model: {
    //表名
    type: String,
    default: '',
  },
  limit: {
    //可上传数量
    type: Number,
    default: 1,
  },
})

// 在子组件内部定义一个响应式的 fileListCopy，以便独立追踪和操作
const fileList = ref([])

import { ref } from 'vue'

import { ElLoading, ElMessage, UploadFile } from 'element-plus'
import { api_upload_base64, api_upload_file } from '/@/api/files'
const $baseMessage = inject<any>('$baseMessage')
const baseurl = `${import.meta.env.VITE_APP_BASE_URL}`

//---------------------------
//图片组建粘贴
const uploadRef = ref<any>(null)
//初始化粘贴准备
const startPasteProcess = () => {
  console.log('请粘贴内容')
  window.addEventListener('paste', handlePaste) // 监听粘贴事件
}
//粘贴操作
const handlePaste = (event: ClipboardEvent) => {
  const items = (event.clipboardData || (event as any).originalEvent.clipboardData).items

  if (!items || items.length === 0) {
    ElMessage({
      message: '当前浏览器不支持本地',
      type: 'error',
    })
    return
  }

  let file = ''
  // 搜索剪切板items
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      file = items[i].getAsFile()
      break
    }
  }
  if (!file) {
    // ElMessage({
    //   message: '粘贴内容非图片',
    //   type: 'warning',
    // })
    return
  }
  convertToBase64(file, (base64Str: any) => {
    uploadFile(base64Str)
  })
}
//粘贴转base64
const convertToBase64 = (file: any, callback: any) => {
  const reader = new FileReader()
  reader.onload = (event) => {
    callback(event.target.result)
  }
  reader.readAsDataURL(file)
}
//进行粘贴上传
const uploadFile = (base64Str: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  console.log('上传前', base64Str)
  api_upload_base64({ img: base64Str }).then((res: any) => {
    console.log('上传后', res)
    loading.close()
    if (res.code == 200) {
      //表示上传成功，向files_file文件里插入
      api_upload_file(res).then((r: any) => {})
    }
  })
}

//粘贴准备
onMounted(() => {
  console.log('组件已显示')
  startPasteProcess()
})
//粘贴取消
onBeforeUnmount(() => {
  // 组件卸载时移除监听器
  console.log('已移出')
  window.removeEventListener('paste', handlePaste)
})

const emit = defineEmits(['get-data'])
//上传成功
const OnSuccess = (res: any, file: any) => {
  console.log('上传成功', res)
  if (res.code == 200) {
    //表示上传成功，向files_file文件里插入
    fileList.value = [] //上传成功后归零
    emit('get-data', file, props.field)
  }
  if (res.code == 1) {
    //表示上传成功，向files_file文件里插入
    $baseMessage(res.msg, 'error', 'hey')
  }
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

//移出图片
const handleRemove = (file: UploadFile) => {
  emit('remove-data', file, props.field)
}
//展示图片
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
//下载图片
const handleDownload = (file: UploadFile) => {
  window.open(file.url, '_blank')
}
</script>
<style scoped lang="scss">
.upload-file .hide {
  :deep(.el-upload--picture-card) {
    display: none;
  }
}
</style>
